/*
 * @Date: 2022-06-16 14:09:57
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-06-24 14:33:43
 * @FilePath: \taro-music-learn\src\store\playSong\index.ts
 * @Description: 当前歌曲播放信息
 */
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { reqSongDetailAction, reqLyric } from "@/api/songs";
import { PromiseFormat } from "@/utils/request";
import { parseLyric, getRandomIntInclusive } from "@/utils";
export type TPlaySongInfo = {
  id: number;
  name: string;
  ar: Array<{
    name: string;
  }>;
  al: {
    picUrl: string;
    name: string;
  };
  url: string;
  dt: number; // 总时长，ms
  st: number; // 是否喜欢}
};
export interface IPlaySongState {
  currentSong: TPlaySongInfo;
  currentSongIndex: number;
  playList: Array<any>;
  sequence: number;
  lyricList: Array<any>;
  currentLyricIndex: number;
  isPlaying: boolean;
  timeStamp: number;
}
//获取歌词信息
export const fetchSongDetailInfo = createAsyncThunk(
  "PlaySongSlice/fetchSongDetailInfo",
  async (ids: string | number, thunkAPI) => {
    const res = await reqSongDetailAction(ids);
    if (res.data.code === 200) {
      thunkAPI.dispatch(fetchLyricById(ids));
    }
    return PromiseFormat(res.data);
  }
);
const fetchLyricById = createAsyncThunk(
  "PlaySongSlice/fetchLyricById",
  async (ids: string | number) => {
    let res = await reqLyric(ids);
    return PromiseFormat(res.data);
  }
);
const initialState: IPlaySongState = {
  currentSong: {
    id: 0,
    name: "",
    ar: [],
    al: {
      picUrl: "",
      name: ""
    },
    url: "",
    dt: 0, // 总时长，ms
    st: 0 // 是否喜欢
  },
  currentSongIndex: 0,
  playList: [],
  sequence: 0,
  lyricList: [],
  currentLyricIndex: 0,
  isPlaying: false,
  timeStamp: 0
};
export const PlaySongSlice = createSlice({
  name: "PlaySongSlice",
  initialState,
  reducers: {
    changeCurrentSongBySequence: (state, action) => {
      state.timeStamp = Date.now();
      const playList = state.playList;
      let curIndx = state.currentSongIndex;
      const sequence = state.sequence;
      if (sequence === 1) {
        let randomIndex = getRandomIntInclusive(
          0,
          playList.length - 1,
          curIndx
        );
        curIndx = randomIndex;
      } else if (sequence === 2) {
        curIndx = curIndx;
      } else {
        curIndx = curIndx + action.payload;
        if (curIndx >= playList.length) {
          curIndx = 0;
        }
        if (curIndx < 0) {
          curIndx = playList.length - 1;
        }
      }
      state.currentSongIndex = curIndx;
      state.currentSong = playList[curIndx];
      state.currentLyricIndex = 0;
    },
    toggelStatePlayFlag: (state, action) => {
      state.isPlaying = action.payload;
    },
    updateSequence: (state, action) => {
      state.sequence = action.payload;
    },
    updateCurrentLyricIndex: (state, action) => {
      state.currentLyricIndex = action.payload;
    },
    deleteSongById: (state, action) => {
      state.playList = state.playList.filter(item => {
        return item.id !== action.payload;
      });
      console.log("删除后的数组", state.playList);
    }
  },
  extraReducers: {
    [fetchSongDetailInfo.fulfilled.type]: (state, action) => {
      const songIndex = state.playList.findIndex(item => {
        return item.id === action.payload.songs[0].id;
      });
      if (songIndex === -1) {
        const newPalyList = [...state.playList];
        newPalyList.push(action.payload.songs[0]);
        state.playList = newPalyList;
        state.currentSongIndex = newPalyList.length - 1;
        state.currentSong = action.payload.songs[0];
      } else {
        const newPalyList = [...state.playList];
        state.currentSongIndex = songIndex;
        state.currentSong = newPalyList[songIndex];
      }
    },
    [fetchLyricById.fulfilled.type]: (state, action) => {
      const lyricList = parseLyric(action.payload.lrc.lyric);
      state.lyricList = lyricList;
    }
  }
});
export const {
  changeCurrentSongBySequence,
  toggelStatePlayFlag,
  updateSequence,
  updateCurrentLyricIndex,
  deleteSongById
} = PlaySongSlice.actions;
